/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ajz.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.ajz.entity.AjzCompanyInfo;
import com.jeesite.modules.ajz.dao.AjzCompanyInfoDao;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintViolationException;

/**
 * 企业信息表Service
 * @author cww
 * @version 2019-01-11
 */
@Service
@Transactional(readOnly=true)
public class AjzCompanyInfoService extends CrudService<AjzCompanyInfoDao, AjzCompanyInfo> {

	private Map<String,String> tel ;//联系人电话
	private Map<String,String> addr;//地址
	private String id;

	/**
	 * 获取单条数据
	 * @param ajzCompanyInfo
	 * @return
	 */
	@Override
	public AjzCompanyInfo get(AjzCompanyInfo ajzCompanyInfo) {
		return super.get(ajzCompanyInfo);
	}
	
	/**
	 * 查询分页数据
	 * @param ajzCompanyInfo 查询条件
	 * @param ajzCompanyInfo.page 分页对象
	 * @return
	 */
	@Override
	public Page<AjzCompanyInfo> findPage(AjzCompanyInfo ajzCompanyInfo) {
		return super.findPage(ajzCompanyInfo);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param ajzCompanyInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(AjzCompanyInfo ajzCompanyInfo) {
//		super.save(ajzCompanyInfo);
		this.preSave(ajzCompanyInfo);
		if (ajzCompanyInfo.getIsNewRecord()) {
			ajzCompanyInfo.preInsert();
			ajzCompanyInfo.setId(UUID.randomUUID().toString().replaceAll("-",""));
			this.insert(ajzCompanyInfo);
		} else {
			ajzCompanyInfo.preUpdate();
			AjzCompanyInfo oldAjzCompanyInfo = get(ajzCompanyInfo);
			ajzCompanyInfo.setCreateBy(oldAjzCompanyInfo.getCreateBy());
			ajzCompanyInfo.setCreateDate(oldAjzCompanyInfo.getCreateDate());
			ajzCompanyInfo.setStatus(oldAjzCompanyInfo.getStatus());
			this.update(ajzCompanyInfo);
		}
	}
	
	/**
	 * 更新状态
	 * @param ajzCompanyInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(AjzCompanyInfo ajzCompanyInfo) {
		super.updateStatus(ajzCompanyInfo);
	}
	
	/**
	 * 删除数据
	 * @param ajzCompanyInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(AjzCompanyInfo ajzCompanyInfo) {
		super.delete(ajzCompanyInfo);
	}


	/**
	 * 导入用户数据
	 * @param file 导入的用户数据文件
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 */
	@Transactional(readOnly=false)
	public String importData(MultipartFile file, Boolean isUpdateSupport) {
		if (file == null){
			throw new ServiceException("请选择导入的数据文件！");
		}
		int successNum = 0; int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		try(ExcelImport ei = new ExcelImport(file, 2, 0)){
			List<AjzCompanyInfo> list = ei.getDataList(AjzCompanyInfo.class);
			for (AjzCompanyInfo ajzCompanyInfo : list) {
				try{
					boolean hasCompanyInfo = hasAjzCompanyInfo(ajzCompanyInfo);
					if (isUpdateSupport){
						hasCompanyInfo = false;
					}
					if (hasCompanyInfo){
						this.save(ajzCompanyInfo);
						successNum++;
						successMsg.append("<br/>" + successNum + "、账号 " + ajzCompanyInfo.getEnterpriseName() + " 导入成功");
					} else{
						ajzCompanyInfo.setId(id);
						this.save(ajzCompanyInfo);
						successNum++;
						successMsg.append("<br/>" + successNum + "、账号 " + ajzCompanyInfo.getEnterpriseName() + " 更新成功");
					}
//					if (isUpdateSupport)
//					else {
//						failureNum++;
//						failureMsg.append("<br/>" + failureNum + "、账号 " + ajzCompanyInfo.getEnterpriseName() + " 已存在");
//					}
				} catch (Exception e) {
					failureNum++;
					String msg = "<br/>" + failureNum + "、账号 " + ajzCompanyInfo.getEnterpriseName() + " 导入失败：";
					if (e instanceof ConstraintViolationException){
						List<String> messageList = ValidatorUtils.extractPropertyAndMessageAsList((ConstraintViolationException)e, ": ");
						for (String message : messageList) {
							msg += message + "; ";
						}
					}else{
						msg += e.getMessage();
					}
					failureMsg.append(msg);
					logger.error(msg, e);
				}
			}
		} catch (Exception e) {
			failureMsg.append(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		}else{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}


	//更新验证企业的相关变量
	public void updateVariable(){
		List<AjzCompanyInfo> companyInfos = dao.findAllList();
		tel = new HashMap<String,String>();
		addr = new HashMap<String,String>();
		for (AjzCompanyInfo ajzCompanyInfo :companyInfos){
			if(!(ajzCompanyInfo.getContactPersonTel()==null||"".equals(ajzCompanyInfo.getContactPersonTel()))){
				tel.put(ajzCompanyInfo.getContactPersonTel(),ajzCompanyInfo.getId());
			}
			if(!(ajzCompanyInfo.getAddr()==null||"".equals(ajzCompanyInfo.getAddr()))){
				addr.put(ajzCompanyInfo.getAddr(),ajzCompanyInfo.getId());
			}

		}
	}

	//检查数据库是否存在要添加的企业
	private boolean hasAjzCompanyInfo(AjzCompanyInfo ajzCompanyInfo){
		id=null;
		String key = getKey(ajzCompanyInfo.getContactPersonTel());
		if(tel.size()!=0){
			if(!"".equals(key)){
				id = tel.get(key);
			}
		}
		//	当电话号码及地址都不同时，或者有一个不同时，插入数据，返回值为true，及处理同个商人多个店面的情况
		//	当电话号码及地址相同时，修改数据,返回值为false
		if(id==null||"".equals(id)){//没有存在商家的电话号码
			return true;
		}else{
			if(addr.size()!=0){
				key = getKey(ajzCompanyInfo.getAddr());
				if(!"".equals(key)){
					id = addr.get(key);
					if(id==null){//没有存在商家的地址
						return true;
					}
				}
			}
		}
		return false;
	}

	private String getKey(String key){
		if(key==null){
			return  "";
		}
		return key;
	}

}